import React, { useState } from 'react';
import { Table, Input, InputNumber, Popconfirm, Form, Typography } from 'antd';
import type { Dispatch } from 'umi';
import type { Item } from '../../index';

interface EditableCellProps extends React.HTMLAttributes<HTMLElement> {
  editing: boolean;
  dataIndex: string;
  title: any;
  inputType: 'number' | 'text';
  record: Item;
  index: number;
  children: React.ReactNode;
}

const EditableCell: React.FC<EditableCellProps> = ({
  editing,
  dataIndex,
  title,
  inputType,
  record,
  index,
  children,
  ...restProps
}) => {
  const inputNode = inputType === 'number' ? <InputNumber /> : <Input />;
  return (
    <td {...restProps}>
      {editing ? (
        <Form.Item
          name={dataIndex}
          style={{
            margin: 0,
          }}
          rules={[
            {
              required: true,
              message: `Please Input ${title}!`,
            },
          ]}
        >
          {inputNode}
        </Form.Item>
      ) : (
        children
      )}
    </td>
  );
};

interface IPrepareTableProps {
  role: number;
  dataSource: any[];
  columns: any[];
  dispatch?: Dispatch;
}

const PrepareTable: React.FC<IPrepareTableProps> = (props) => {
  const [form] = Form.useForm();
  const [editingKey, setEditingKey] = useState('');
  const [data, setData] = useState(props.dataSource);
  const isEditing = (record: Item) => record.key === editingKey;
  const save = async (key: React.Key) => {
    try {
      const row = await form.validateFields();
      const newData = [...data];
      const index = newData.findIndex((item) => key === item.key);
      if (index > -1) {
        const $item = newData[index];
        newData.splice(index, 1, { ...$item, ...row });
        const rowData = newData.filter((item) => item.key === key);
        try {
          if (props.dispatch) {
            props.dispatch({
              type: 'quota/fetchSaveEditRowData',
              payload: {
                rowData,
                role: props.role,
              },
            });
          }
          setData(newData);
          setEditingKey('');
        } catch (e) {
          console.log(e);
        }
      } else {
        newData.push(row);
        setData(newData);
        setEditingKey('');
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };
  const edit = (record: Partial<Item> & { key: React.Key }) => {
    form.setFieldsValue({
      firstLevel: '',
      secondLevel: '',
      score: '',
      ...record,
    });
    setEditingKey(record.key);
  };

  const cancel = () => {
    setEditingKey('');
  };
  let columns = (() => {
    const $columns = [...props.columns];
    $columns.push({
      title: 'operation',
      dataIndex: 'operation',
      width: 750 / 4,
      render: (_: any, record: Item) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <a
              href=""
              onClick={(e: any) => {
                e.preventDefault();
                save(record.key);
              }}
              style={{ marginRight: 8 }}
            >
              Save
            </a>
            <Popconfirm title="Sure to cancel?" onConfirm={cancel}>
              <a>Cancel</a>
            </Popconfirm>
          </span>
        ) : (
          <Typography.Link disabled={editingKey !== ''} onClick={() => edit(record)}>
            Edit
          </Typography.Link>
        );
      },
    });
    return [...$columns];
  })();

  columns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }

    return {
      ...col,
      onCell: (record: Item) => ({
        record,
        inputType: 'text',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });
  return (
    <div>
      <Form form={form} component={false}>
        <Table
          components={{
            body: {
              cell: EditableCell,
            },
          }}
          bordered
          dataSource={data}
          columns={columns}
          rowClassName="editable-row"
          pagination={false}
        />
      </Form>
    </div>
  );
};

export default PrepareTable;
